package com.m7788.screen;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.bill99mpp.demo.rsa.MerchantConfig;
import com.bill99mpp.demo.rsa.RSATool;
import com.imagemanager.util.CacheService;
import com.m7788.dao.HUrlDaoImpl;
import com.m7788.dao.UploadProDataDaoImpl;
import com.m7788.po.HistoryUrl;
import com.m7788.po.UploadInfo;
import com.m7788.po.UploadProData;
import com.m7788.po.UploadResult;
import com.m7788.util.AppUtil;
import com.m7788.util.Constant;
import com.m7788.util.DialogTips;
import com.m7788.util.DialogTips.OnChooseTipListener;
import com.m7788.util.DialogUploadFile;
import com.m7788.util.DialogUploadFile.OnChooseFileListener;
import com.m7788.util.HtmlChromeClient;
import com.m7788.util.HtmlChromeClient.OnProgressChangedListener;
import com.m7788.util.HtmlInterface;
import com.m7788.util.HtmlWebViewClient;
import com.m7788.util.HtmlWebViewClient.OnJsWebViewListener;
import com.m7788.util.MoveDistanceGetRunnable.OnMoveListener;
import com.m7788.util.GaodeLocationManager;
import com.m7788.util.HttpService;
import com.m7788.util.ImageUpload;
import com.m7788.util.FileDownloadUtil;
import com.m7788.util.MoveDistanceGetRunnable;
import com.m7788.util.NetDiagnosesUtil;
import com.m7788.util.ResizeLayout;
import com.m7788.util.ShareUtil;
import com.m7788.util.UpdateUtil;
import com.m7788.widget.MyListener;
import com.m7788.widget.PullToRefreshLayout;
import com.qmoney.third.OrderInfo;
import com.qmoney.third.PayRequest;
import com.qmoney.ui.PayService;
import com.tool.custom.textview.CBadgeView;
import com.tool.utils.DBUtil;
import com.tool.utils.DataUtil;
import com.tool.utils.DateUtil;
import com.tool.utils.LogUtil;
import com.tool.utils.LogoutUtil;
import com.tool.utils.StrUtils;

@SuppressLint("SimpleDateFormat")
public class IndexScreen extends ActivityGroup implements OnClickListener,
		OnJsWebViewListener,OnMoveListener{
	CBadgeView badge1;
	ImageView mIvBack, mIvForward, mIvToTop, mIvToBottom, mIvRefresh, mIvToHome;
	Button  button7;
	TextView tv_left, tv_left_m, tv_menu, tv_right;
	ImageView iv_pro, iv_mess;
	RelativeLayout rl_left, rl_left_m, rl_right;
	LinearLayout llytEmpty;
	TextView tvReload;
	SwipeRefreshLayout swipeLayout;
	private AnimationDrawable animPro;
	// float widths;
	// private PullToRefreshWebView pullToRefreshWebView;
	private PullToRefreshLayout pullToRefreshLayout;
	private WebView mWebView = null;
	private ImageView mIvLeftIcon,mIvRightIcon;
	public Handler handler = new Handler();
	String value;
	HtmlWebViewClient hwvc;
	HtmlInterface hif;
	Map<String, String> parmasMap;
	String url;
	CommandReceiver cmdReceiver;
	SoundPool soundPool;
	private Vibrator vibrator;
	HashMap<Integer, Integer> soundPoolMap;
	ResizeLayout parent;
	LinearLayout ll_btns,llyt_content;
	private RelativeLayout rl_top;
	private boolean anmiFlag = false;
	private String userId;
	private String tipContent, tipUrl, tipNid;
	private boolean isTips = true;
	AlertDialog aDialog;
	private String wapFrom;
	private String type;// 动作类型
	private String params;// 参数集合
	String gpid, gFolderName;
	private String Oper;// 判断来源
	UploadProData proData;
	Long gDataId;
	int curing = 0;
	List<String> selecImags;
	float xDown, yDown, xUp, yUp;
	public static boolean isCallback = false;
	public static boolean isPullUp = false;
	private MediaPlayer mediaPlayer = new MediaPlayer();
	private int moveOffset = 200;   //300
	private int upBounds = 200;     //400
	
	private int menuShowOffset = 200;
	private int menuDisOffset = 0;
	private LinearLayout guide1, guide2, guide3, guide4;
	private ViewPager viewPager;
	private List<View> viewList;
	private RelativeLayout mRlytGuide;
	private ImageView mIvPoint1,mIvPoint2,mIvPoint3,mIvPoint4;
	private boolean isBottomMenuShow = false;
	private int windowHeight,windowWidth;
	private int bottomMenuHeight;
	private LinearLayout mLlytProgress;
	private View mProgress;
	public static boolean isWebControl = false;
	private boolean canShowBottomMenu = true;
	public interface OnLoadStartListener{
		public void onLoadStart();
	}
	private class CommandReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(Constant.ACTION_STOA)) {
				Bundle bundle = intent.getExtras();
				int operation = bundle.getInt("operation", -1);
				String desc = bundle.getString("desc");
				if (operation == 55) {
					String tip = AppUtil.getRecord(IndexScreen.this,
							Constant.INDEX_TITLE_LEFT_TEXT);
					String tipd = AppUtil.getRecord(IndexScreen.this,
							Constant.INDEX_TITLE_LEFT_TEXT_DEFAULT);

					if (tip.length() > 0) {
						tv_left.setText(tip);
					} else if (tipd.length() > 0) {
						tv_left.setText(tipd);
					}

				} else if (operation == 57) {
					String tip = AppUtil.getRecord(IndexScreen.this,
							Constant.INDEX_TITLE_LEFT_TEXT2);
					if (tip.length() > 0)
						tv_left_m.setText(tip);

				} else if (operation == 56) {
					String tip = AppUtil.getRecord(IndexScreen.this,
							Constant.INDEX_TITLE_RIGHT_TEXT);
					String num = AppUtil.getRecord(IndexScreen.this,
							Constant.INDEX_TITLE_RIGHT_NUM);

					if (tip.length() > 0) {
						if (Integer.parseInt(num) > 0) {
							String sound = AppUtil.getRecord(IndexScreen.this,
									Constant.SOUND_KEY);
							String shake = AppUtil.getRecord(IndexScreen.this,
									Constant.SHAKE_KEY);
							if (sound.equals("open")) {
								playSound(1); // 播放声音
							}
							if (shake.equals("open")) {
								vibrator.vibrate(200);
							}
						}
						tv_right.setText(tip);
						badge1.setText(num);
						badge1.show();
						iv_mess.setVisibility(View.VISIBLE);
					} else {
						tv_right.setText("");
						iv_mess.setVisibility(View.GONE);
						badge1.setText("");
						badge1.hide();
					}

					// 1是更新数据库，2是上传成功 3失败
				} else if (operation == 2) {
					DataUtil.deleFileInFolder(ImageUpload.getInstance(
							IndexScreen.this).getFileDir());
					System.gc();
				} else if (operation == 1) {

				} else if (operation == 120) {
				} else if (operation == 8888) {// 支付接口
					PayRequest request = getPayRequest();
					if (null != request) {
						// 调用支付接口
						mWebView.goBack();
						PayService.pay(request);
					}
				} else if (operation == 200) {// 显示头部和底部菜单
					// rl_top.setVisibility(View.VISIBLE);
					// ll_btns.setVisibility(View.VISIBLE);
				} else if (operation == 201) {// 隐藏头部菜单
					// rl_top.setVisibility(View.GONE);
				} else if (operation == 202) {// 隐藏底部菜单
					// ll_btns.setVisibility(View.GONE);
				} else if (operation == 203) {// 分享
					String[] info = desc.split(";");
					if (info.length == 5) {
						new ShareUtil(IndexScreen.this).showShare(info[0],
								info[1], info[2], info[3], info[4]);
					} else if (info.length == 4) {
						new ShareUtil(IndexScreen.this).showShare(info[0],
								info[1], info[2], info[3], "");
					}
				} else if (operation == 204) {// 微信、支付宝 支付成功
					DataUtil.showShortToast(IndexScreen.this, ("支付成功"));
					// AppUtil.saveRecord(IndexScreen.this,
					// Constant.PAY_LIST_URL_FLAG, "true");
					payResult(true);
					// new PayAsyncTask().execute();
				} else if (operation == 205) {// 推送注册userid
					userId = AppUtil.getRecord(IndexScreen.this,
							Constant.USERID);
					startAlias();
				} else if (operation == 206) {// 支付宝支付结果
					DataUtil.showShortToast(IndexScreen.this, ("支付结果确认中"));

				} else if (operation == 207) {// 微信、支付宝支付结果
					DataUtil.showShortToast(IndexScreen.this, ("支付失败"));
					payResult(false);
				} else if (operation == 208) {// 通知传url
					if (StrUtils.isNotEmpty(desc)) {
						forwardUrl(desc);
					}
				} else if (operation == 209) {// 通知打开dialog
					if (StrUtils.isNotEmpty(desc) && isTips) {
						// if(aDialog !=null ){
						// aDialog.cancel();
						//
						// }
						String[] tips = desc.split("##");
						Log.e("aaaa", desc);
						if (tips.length == 3) {
							tipUrl = tips[1];
							tipContent = tips[0];
							tipNid = tips[2];
							// showDialogForTips();
						}
					}
				} else if (operation == 366) {// 通知打开dialog
					String tip = "";
					int platform = Integer.parseInt(desc);
					if(0 == platform){
						tip = "正在跳转至QQ，请耐心等待!";
					}else if(1 == platform){
						tip = "正在跳转至微博，请耐心等待!";
					}else if(2 == platform){
						tip = "正在跳转至微信，请耐心等待!";
					}
					DataUtil.showShortToast(context, tip);
					new ShareUtil(IndexScreen.this, mWebView).login(platform);
				} else if (operation == 466) {// 通知打开dialog
					PullToRefreshLayout.canPullDown = "1".equals(desc);
				}else if(operation == 501){
					SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(IndexScreen.this);
					SharedPreferences.Editor editor = mSharedPreferences.edit();
					editor.putBoolean("canZoom","1".equals(desc));
					editor.commit();
					mWebView.getSettings().setSupportZoom("1".equals(desc));
					mWebView.getSettings().setBuiltInZoomControls("1".equals(desc));
					mWebView.getSettings().setUseWideViewPort(mSharedPreferences.getBoolean("canZoom",false));
				} else {
					forwardUrl(mWebView.getUrl());
				}
			} else if (intent.getAction().equals("com.sharesdk.do")) {
				// 预防多次点击分享，做限制
				HtmlInterface.isShare = false;
			}else if(intent.getAction().equals("com.control.bottombar")){
				int flag = intent.getIntExtra("flag", 1);
				if(flag == 1){
					canShowBottomMenu = true;
					LayoutParams params = (LayoutParams) ll_btns.getLayoutParams();
					params.height = bottomMenuHeight;
					ll_btns.setLayoutParams(params);
					isBottomMenuShow = true;
				}else{
					canShowBottomMenu = false;
					LayoutParams params = (LayoutParams) ll_btns.getLayoutParams();
					params.height = 0;
					ll_btns.setLayoutParams(params);
					isBottomMenuShow = false;
				}
			}else if(intent.getAction().equals("com.control.progress")){
				mLlytProgress.setVisibility(View.VISIBLE);
				setProgress(0);
			}
		}
	}

	private void showDialogForTips() {
		aDialog = new AlertDialog.Builder(this)
				.setTitle("提示")
				.setMessage(tipContent)
				.setPositiveButton("查看", new DialogInterface.OnClickListener() { // 设置确定按钮
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss(); // 关闭dialog
								forwardUrl(tipUrl);
								NotificationManager manger = (NotificationManager) IndexScreen.this
										.getSystemService(NOTIFICATION_SERVICE);
								manger.cancel(Integer.valueOf(tipNid));
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() { // 设置取消按钮
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						}).create();

		aDialog.show();
	}

	/**
	 * 
	 * 方法名：payResult 功能：支付结果跳转 参数：
	 * 
	 * @param isSucc
	 *            创建人：huanghaishui 创建时间：2015-11-13
	 */
	private void payResult(boolean isSucc) {
		String url = AppUtil.getRecord(IndexScreen.this, Constant.PAY_BACK_URL);

		url += "?subject="
				+ AppUtil.getRecord(IndexScreen.this, Constant.PAY_PROD_NAME);
		url += "&real_money="
				+ AppUtil.getRecord(IndexScreen.this, Constant.PAY_AMD);
		url += "&out_trade_no="
				+ AppUtil.getRecord(IndexScreen.this, Constant.PAY_ORDER_ID);
		;
		url += "&user_ID="
				+ AppUtil.getRecord(IndexScreen.this, Constant.PAY_USER_ID);
		if (isSucc) {
			url += "&back_state=true";
		} else {
			url += "&back_state=false";
		}
		LogUtil.e("payResultUrl", url);
		mWebView.loadUrl(url);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("Chenguangxi","start");
		NetDiagnosesUtil.postDiagnoseData(this);
		SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(IndexScreen.this);
		SharedPreferences.Editor editor = mSharedPreferences.edit();
		editor.putBoolean("canZoom",false);
		editor.commit();
		setContentView(R.layout.web_screen);
		getContentResolver().registerContentObserver(
				Uri.parse("content://sms"), true,
				new SmsObserver(new Handler()));
		LogoutUtil.getInstance().addActivity(this);
		vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
		// JPushInterface.init(IndexScreen.this.getApplicationContext());
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		windowHeight = dm.heightPixels - getStatusHeight(this);
		windowWidth = dm.widthPixels;
		bottomMenuHeight = getResources().getDimensionPixelOffset(R.dimen.bottom_menu_height);
		initView();
		initWebView();
		initSoundPool();
		cmdReceiver = new CommandReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constant.ACTION_STOA);
		filter.addAction("com.sharesdk.do");
		filter.addAction("com.control.bottombar");
		filter.addAction("com.control.progress");
		registerReceiver(cmdReceiver, filter);
		if(!hasInternet(this)){
			llytEmpty.setVisibility(View.VISIBLE);
			tvReload.setOnClickListener(new OnClickListener() {				
				@Override
				public void onClick(View v) {
					onCreate(null);
				}
			});
			return;
		}else{
			llytEmpty.setVisibility(View.GONE);
		}
		initPayment();
		// 相册相关
		String orderFlag = AppUtil.getRecord(IndexScreen.this,
				Constant.ALBUM_ORDER);
		if ("true".equals(orderFlag)) {
			CacheService.setImageOrderAsc(true);
		} else {
			CacheService.setImageOrderAsc(false);
		}
		// userId = "hhs:linkai";
		// startAlias();
		CacheService.computeDirtySets(IndexScreen.this);
		CacheService.startCache(IndexScreen.this, true);
		UpdateQueryAsyncTask ut = new UpdateQueryAsyncTask();
		ut.execute();
	}
	

	/*
	 * private void initIndicator() { ILoadingLayout startLabels =
	 * pullToRefreshWebView .getLoadingLayoutProxy(true, false);
	 * startLabels.setPullLabel("下拉刷新");// 刚下拉时，显示的提示
	 * startLabels.setRefreshingLabel("正在刷新...");// 刷新时
	 * startLabels.setReleaseLabel("释放立即刷新");// 下来达到一定距离时，显示的提示
	 * 
	 * ILoadingLayout endLabels = pullToRefreshWebView.getLoadingLayoutProxy(
	 * false, true); endLabels.setPullLabel("就把我往死里面拉吧123...");// 刚下拉时，显示的提示
	 * endLabels.setRefreshingLabel("正在刷新123...");// 刷新时
	 * endLabels.setReleaseLabel("放了我，我就刷新123...");// 下来达到一定距离时，显示的提示 }
	 */

	/**
	 * 
	 * 方法名：initPayment 功能：初始化支付 参数： 创建人：huanghaishui 创建时间：2014-1-9
	 */
	private void initPayment() {
		// 初始化商户私钥
		try {
			RSATool.init(getAssets().open(MerchantConfig.PRIVATE_KEY_PATH));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * 方法名：getPayRequest 功能：调用支付接口 参数：
	 * 
	 * @return 创建人：huanghaishui 创建时间：2014-1-9
	 */
	private PayRequest getPayRequest() {

		String orderId = AppUtil.getRecord(this, Constant.PAY_ORDER_ID);
		String amt = AppUtil.getRecord(this, Constant.PAY_AMD);
		String merchantName = AppUtil.getRecord(this,
				Constant.PAY_MERCHANT_NAME);
		String productName = AppUtil.getRecord(this, Constant.PAY_PROD_NAME);
		String partnerUserId = AppUtil.getRecord(this, Constant.PAY_USER_ID);
		String unitPrice = AppUtil.getRecord(this, Constant.PAY_PRICE);
		String total = AppUtil.getRecord(this, Constant.PAY_TOTAL);

		PayRequest payRequest = null;

		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = sdf.format(new Date());

		// 设置订单信息
		OrderInfo order = new OrderInfo();
		order.setOrderId(orderId); // 订单号
		order.setAmt(amt); // 订单金额
		order.setMerchantName(merchantName); // 商户名称
		order.setProductName(productName); // 商品名称
		order.setUnitPrice(unitPrice);
		order.setTotal(total);
		order.setMerchantOrderTime(date); // 订单时间

		String orderSignSrc = PayService.generateOrderSignSrc(order); // 调用插件api生成待签名的源串
		String orderSign = RSATool.sign(orderSignSrc);// 商户客户端调用商户服务器接口对订单加签
		order.setOrderSign(orderSign); // 设置订单签名
		String callbackPackageName = "com.m7788.screen";// 支付后回调商户的intent包名
		String callbackClassName = "com.m7788.screen.PaymentScreen";// 支付后回调商户的intent完整类名

		String querySignSrc = PayService.generateCardQuerySignSrc(
				MerchantConfig.MEMBERCODE, MerchantConfig.MERCHANTID,
				partnerUserId);
		String querySign = RSATool.sign(querySignSrc);// 设置卡列表查询签名
		order.setQuerySign(querySign);

		payRequest = new PayRequest(IndexScreen.this, IndexScreen.class,
				mWebView, callbackPackageName, callbackClassName, // 接收支付后回调
				MerchantConfig.MEMBERCODE, // 商户会员号
				MerchantConfig.MERCHANTID, // 商户号
				partnerUserId, // 用户标识
				null, null, null, // 可指定用户卡信息
				MerchantConfig.URL_TEST_SERVER, // 订单提交地址
												// ，正式投产时要切换到生产环境
				order); // 订单对象

		return payRequest;
	}

	private void initSoundPool() {
		soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
		soundPoolMap = new HashMap<Integer, Integer>();
		soundPoolMap.put(1, soundPool.load(this, R.raw.open, 1));
	}
	
	private void playSound(int sound){
		if(!TextUtils.isEmpty(AppUtil.getRecord(getApplicationContext(), Constant.RECORD_NAME_KEY))){
			String pathName = Environment.getExternalStorageDirectory().getAbsoluteFile()+File.separator+"7788"+File.separator+AppUtil.getRecord(getApplicationContext(), Constant.RECORD_NAME_KEY);
			File file = new File(pathName);
			if(file.exists()){
				mediaPlayer.stop();
				mediaPlayer.reset();
				try {
					mediaPlayer.setDataSource(pathName);
					mediaPlayer.prepare();
					mediaPlayer.start();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				playSoundPool(1);
			}
		}else{
			playSoundPool(1);
		}
	}

	public void playSoundPool(int sound) {
		int soundId = Integer.valueOf(soundPoolMap.get(sound).toString());
		AudioManager mgr = (AudioManager) this
				.getSystemService(Context.AUDIO_SERVICE);
		float streamVolumeCurrent = mgr
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		float streamVolumeMax = mgr
				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		float volume = streamVolumeCurrent / streamVolumeMax;
		soundPool.play(soundId, volume, volume, 1, 0, 1f);
	}

	private String toURLEncoded(String paramString) {
		if (paramString == null || paramString.equals("")) {
			return "";
		}
		try {
			String str = new String(paramString.getBytes(), "UTF-8");
			str = URLEncoder.encode(str, "UTF-8");
			return str;
		} catch (Exception localException) {
		}
		return "";
	}

	@Override
	protected void onStart() {
		GaodeLocationManager.startLocation(this, new AMapLocationListener() {

			@Override
			public void onLocationChanged(final AMapLocation location) {
				if (location != null) {
					TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
					final String szImei = TelephonyMgr.getDeviceId();
					new Thread(new Runnable() {

						@Override
						public void run() {
							JSONObject jsonObject = new JSONObject();
							try {
								jsonObject.put(Constant.CITY,
										toURLEncoded(location.getCity() + ""));
								jsonObject.put(Constant.LONGITUDE,
										location.getLongitude() + "");
								jsonObject
										.put(Constant.COUNTRY,
												toURLEncoded(location
														.getCountry() + ""));
								jsonObject.put(Constant.PROVINCE,
										toURLEncoded(location.getProvince()
												+ ""));
								jsonObject.put(Constant.DISTRICT,
										toURLEncoded(location.getDistrict()
												+ ""));
								jsonObject.put(Constant.SZIMEI, szImei);
								jsonObject.put(Constant.LATITUDE,
										location.getLatitude() + "");
								jsonObject
										.put(Constant.OSVERSION,
												toURLEncoded("android "
														+ android.os.Build.VERSION.RELEASE));
								jsonObject
										.put(Constant.NAME,
												toURLEncoded(location
														.getStreet()
														+ location
																.getStreetNum()
														+ ""));
								jsonObject
										.put(Constant.MACHINEMODELNAME,
												toURLEncoded(android.os.Build.BRAND
														+ " "
														+ android.os.Build.MODEL));
								jsonObject.put("astoken", AppUtil.getToken(
										getApplicationContext()));
								HttpService.getInstance(IndexScreen.this).postAppInfo(jsonObject);
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}
					}).start();
				}
			}
		});
		checkAndDownLoadMp3(this);
		super.onStart();
	}
	
	private PagerAdapter guidePagerAdapter = new PagerAdapter() {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return (arg0 == arg1);
		}

		@Override
		public int getCount() {
			return viewList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(viewList.get(position));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(viewList.get(position));
			return viewList.get(position);
		}

	};

	private void checkAndDownLoadMp3(final Context context) {
		final String dbTime  = AppUtil.getRecord(getApplicationContext(),
				Constant.TIME_KEY);
		new Thread(new Runnable() {
			@Override
			public void run() {
				String result = HttpService.getInstance(context).set_bell_time();
				if(!TextUtils.isEmpty(result)){
					try {
						JSONObject jsonObject = new JSONObject(result);
						final String time = jsonObject.getString("time");
						final String address = jsonObject.getString("address");
						if (!dbTime.equals(time)
								|| !AppUtil.getRecord(getApplicationContext(),
								Constant.RECORD_KEY).equals(address)) {
							FileDownloadUtil fileDownloadUtil = new FileDownloadUtil(
									new FileDownloadUtil.DownLoadListener() {

										@Override
										public void downLoadSuccess() {
											AppUtil.saveRecord(
													getApplicationContext(),
													Constant.TIME_KEY, time);
											AppUtil.saveRecord(
													getApplicationContext(),
													Constant.RECORD_KEY, address);
											String[] s = address.split("/");
											String fileName = "";
											if (s.length > 0) {
												fileName = s[s.length - 1];
											}
											AppUtil.saveRecord(getApplicationContext(), Constant.RECORD_NAME_KEY, fileName);
										}
									});
							fileDownloadUtil.downFileFromUrl(
									getApplicationContext(),
									jsonObject.getString("address"));
							//
							// AppUtil.saveRecord(getApplicationContext(),
							// Constant.TIME_KEY, jsonObject.getString("time"));
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	private void initWebView() {
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setSavePassword(false);
		webSettings.setSaveFormData(true);
		SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
		webSettings.setSupportZoom(mSharedPreferences.getBoolean("canZoom",false));
		webSettings.setBuiltInZoomControls(mSharedPreferences.getBoolean("canZoom",false));
		//自适应屏幕
		webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setUseWideViewPort(mSharedPreferences.getBoolean("canZoom",false));
		webSettings.setJavaScriptEnabled(true);
		webSettings.setTextZoom(100);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		mWebView.setHorizontalScrollBarEnabled(false);//水平不显示
		mWebView.setVerticalScrollBarEnabled(false); //垂直不显示
		mWebView.addJavascriptInterface(hif, "android");
		mWebView.setWebChromeClient(new HtmlChromeClient(this,
				new OnProgressChangedListener() {

					@Override
					public void onProgressChanged(int newProgress) {
						setLoadingProgress(newProgress);
						if (newProgress == 100) {
							final String wurl = mWebView.getUrl();
							mLlytProgress.setVisibility(View.GONE);
							if (isPullUp) {
								pullToRefreshLayout
										.refreshFinish(PullToRefreshLayout.SUCCEED);
								isPullUp = false;
							}
							/*if(!url.contains("classify.php#item")){
								PullToRefreshLayout.canPullDown = true;
							}
							Constant.sCanHorizontalMove = true;*/
							if(!hasInternet(IndexScreen.this)){
								llytEmpty.setVisibility(View.VISIBLE);
								tvReload.setOnClickListener(new OnClickListener() {				
									@Override
									public void onClick(View v) {
										mWebView.loadUrl(url, parmasMap);
									}
								});
							}else{
								llytEmpty.setVisibility(View.GONE);
							}

							parmasMap.put(Constant.USERAGENT,
									AppUtil.getUserAgent(IndexScreen.this, wurl));
													
						}
					}

				}));
		if(!TextUtils.isEmpty(getIntent().getStringExtra("url"))){
			url = getIntent().getStringExtra("url");
		}else{
			url = Constant.getURL()+"/?" + new Date().getTime();
		}
		forwardUrl(url);
		mLlytProgress.setVisibility(View.VISIBLE);
		//initIndicator();
		mWebView.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(Constant.sCanHorizontalMove == true){
					if (event.getAction() == MotionEvent.ACTION_DOWN) {
						xDown = event.getX();
						yDown = event.getY();
						mIvLeftIcon.setImageResource(R.drawable.icon_left_normal);
						mIvRightIcon.setImageResource(R.drawable.icon_right_normal);
					}else if(event.getAction() == MotionEvent.ACTION_MOVE){
						xUp = event.getX();
						yUp = event.getY();
						if (xUp - xDown < -moveOffset && Math.abs(xDown - xUp) >Math.abs(yUp - yDown)&&Math.abs(yUp - yDown)<upBounds) {
							// 向左滑动
							if(mWebView.canGoForward()){
								mIvRightIcon.setVisibility(View.VISIBLE);
								mIvLeftIcon.setVisibility(View.GONE);
							}
						} else if ((xUp - xDown) > moveOffset
								&& Math.abs(xDown - xUp) >Math.abs(yUp - yDown)&&Math.abs(yUp - yDown)<upBounds) {
							// 向右滑动
							if(mWebView.canGoBack()){
								mIvLeftIcon.setVisibility(View.VISIBLE);
								mIvRightIcon.setVisibility(View.GONE);
							}
						}else{
							mIvLeftIcon.setVisibility(View.GONE);
							mIvRightIcon.setVisibility(View.GONE);
						}
					} else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL) {
						xUp = event.getX();
						yUp = event.getY();
						mIvLeftIcon.setVisibility(View.GONE);
						mIvRightIcon.setVisibility(View.GONE);
						if (xUp - xDown < -moveOffset && Math.abs(xDown - xUp) >Math.abs(yUp - yDown)&&Math.abs(yUp - yDown)<upBounds) {
							// 向左滑动
							mWebView.goForward();
						} else if ((xUp - xDown) > moveOffset
								&& Math.abs(xDown - xUp) >Math.abs(yUp - yDown)&&Math.abs(yUp - yDown)<upBounds) {
							// 向右滑动
							mWebView.goBack();
						}
						if(yUp - yDown < menuDisOffset){
							disButtons();
						}else if(yUp -yDown >menuShowOffset){
							if(canShowBottomMenu){
								showButtons();
							}
						}
					}
				}else{
					mIvLeftIcon.setVisibility(View.GONE);
					mIvRightIcon.setVisibility(View.GONE);
				}
				return false;
			}

			
		});
		mWebView.setOnLongClickListener(new View.OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				final WebView.HitTestResult result = ((WebView) v)
						.getHitTestResult();
				if (null == result)
					return false;
				int type = result.getType();
				if (type == WebView.HitTestResult.UNKNOWN_TYPE)
					return false;
				if (type == WebView.HitTestResult.EDIT_TEXT_TYPE) {

				}
				switch (type) {
				case WebView.HitTestResult.PHONE_TYPE: // 处理拨号
					break;
				case WebView.HitTestResult.EMAIL_TYPE: // 处理Email
					break;
				case WebView.HitTestResult.GEO_TYPE: // TODO
					break;
				case WebView.HitTestResult.SRC_ANCHOR_TYPE: // 超链接
					break;
				case WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE:
					String callback1 = "app_pic_press";
					mWebView.loadUrl("javascript:" + callback1
							+ "('" + result.getExtra() + "')");
					break;
				case WebView.HitTestResult.IMAGE_TYPE: // 处理长按图片的菜单项
					String callback = "app_pic_press";
					mWebView.loadUrl("javascript:" + callback
							+ "('" + result.getExtra() + "')");
					// 获取图片的路径
					break;
				default:
					break;
				}
				return true;
			}
		});

	}
	
	protected void setLoadingProgress(int newProgress) {
		LayoutParams params = (LayoutParams) mProgress.getLayoutParams();
		params.width = windowWidth*newProgress/100;
		mProgress.setLayoutParams(params);
	}

	/**
	 * 获得状态栏的高度
	 * 
	 * @param context
	 * @return
	 */
	public static int getStatusHeight(Context context) {
	    int statusHeight = -1;
	    try {
	        Class<?> clazz = Class.forName("com.android.internal.R$dimen");
	        Object object = clazz.newInstance();
	        int height = Integer.parseInt(clazz.getField("status_bar_height")
	                .get(object).toString());
	        statusHeight = context.getResources().getDimensionPixelSize(height);
	    } catch (Exception e) {
	        e.printStackTrace();
	    }
	    return statusHeight;
	}
	
	private void showButtons() {
		if(isBottomMenuShow == false){
			MoveDistanceGetRunnable moveDistanceGetRunnable = new MoveDistanceGetRunnable(0.0f,bottomMenuHeight, 500, new AccelerateDecelerateInterpolator(), llyt_content, this, 1);
		    moveDistanceGetRunnable.run();
		}
	}

	private void disButtons() {
		if(isBottomMenuShow == true){
			MoveDistanceGetRunnable moveDistanceGetRunnable = new MoveDistanceGetRunnable(bottomMenuHeight,0.0f, 500, new AccelerateDecelerateInterpolator(), llyt_content, this, 0);
		    moveDistanceGetRunnable.run();
		}
	}

	@Override
	protected void onDestroy() {
		if(cmdReceiver!=null){
			this.unregisterReceiver(cmdReceiver);
		}
		getContentResolver()
				.unregisterContentObserver(new SmsObserver(handler));
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.release();
			mediaPlayer = null;
		}
		deleHistory();
		LogoutUtil.getInstance().exit();
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		super.onStop();
		isTips = false;
		AppUtil.saveRecord(this, Constant.ISON, "false");
	}

	@Override
	protected void onResume() {
		System.gc();
		isTips = true;
		AppUtil.saveRecord(this, Constant.ISON, "true");
		// 启动圆形进度条
		if (!anmiFlag) {
			anmiFlag = true;
			handler.postDelayed(new Runnable() {
				public void run() {
					animPro.start();
				}
			}, 50);
		}

		String type = AppUtil.getRecord(this, Constant.TYPE);
		if (!"".equals(type)) {
			AppUtil.saveRecord(this, Constant.TYPE, "");
		}

		// 跳转到支付清单
		String payFlag = AppUtil.getRecord(this, Constant.PAY_LIST_URL_FLAG);
		String partnerUserId = AppUtil.getRecord(this, Constant.PAY_USER_ID);
		if ("true".equals(payFlag)) {
			AppUtil.saveRecord(this, Constant.PAY_LIST_URL_FLAG, "");

			if ("u".equals(partnerUserId.substring(0, 1))) {
				mWebView.loadUrl(Constant.PAY_LIST_USER_URL, parmasMap);

			} else {
				mWebView.loadUrl(Constant.PAY_LIST_SHOPER_URL, parmasMap);
			}

		}

		// 载入历史记录url
		String hisUrl = AppUtil.getRecord(this, Constant.INDEX_HISTORY_URL);
		if (!"".equals(hisUrl)) {
			AppUtil.saveRecord(this, Constant.INDEX_HISTORY_URL, "");
			mWebView.loadUrl(hisUrl, parmasMap);
		}

		// 传图成功回调
		if ("true".equals(AppUtil.getRecord(this, "fabu"))) {
			AppUtil.saveRecord(this, "fabu", "false");
			if (IndexScreen.isCallback) {
				mWebView.loadUrl("javascript:pic_callback()");
			} else {
				mWebView.loadUrl(mWebView.getUrl(), parmasMap);
			}
					
		}

		// 通知的传值
		Bundle bundle = getIntent().getExtras();
		if (bundle != null) {
			String bundleUrl = bundle.getString("bundleUrl");
			if (StrUtils.isNotEmpty(bundleUrl)) {
				mWebView.loadUrl(bundleUrl, parmasMap);
			}
		}
		super.onResume();
	}

	@Override
	public void onJsWebViewEvent(int flag) {

	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			if (mWebView.canGoBack()) {
				mWebView.goBack(); // goBack()表示返回WebView的上一页面
				return true;
			} else {
			}

		}
		return false;
	}

	public String getAppVersionName(Context context) {
		String versionName = "";
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(
					"com.m7788.screen", 0);
			versionName = packageInfo.versionName;
			if (TextUtils.isEmpty(versionName)) {
				return "";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionName;
	}

	private void initView() {
		showModeCheck();
		// DataUtil.showShortToast(IndexScreen.this,"u_id="+
		// "u127".substring(0,1));
		mLlytProgress = (LinearLayout) findViewById(R.id.llyt_progress);
		mProgress = findViewById(R.id.progress);
		ll_btns = (LinearLayout) findViewById(R.id.ws_ll_btns);
		parent = (ResizeLayout) findViewById(R.id.ws_parent);

		rl_top = (RelativeLayout) findViewById(R.id.ws_rl_top);
		llyt_content = (LinearLayout) findViewById(R.id.llyt_content);

		iv_pro = (ImageView) findViewById(R.id.ws_iv_pro);
		iv_mess = (ImageView) findViewById(R.id.ws_iv_mess);
		animPro = (AnimationDrawable) iv_pro.getBackground();

		iv_pro.setVisibility(View.GONE);
		mIvBack = (ImageView) findViewById(R.id.iv_back);
		findViewById(R.id.llyt_back).setOnClickListener(this);

		mIvForward = (ImageView) findViewById(R.id.iv_forward);
		findViewById(R.id.llyt_forward).setOnClickListener(this);

		mIvToTop = (ImageView) findViewById(R.id.iv_toTop);
		findViewById(R.id.llyt_toTop).setOnClickListener(this);

		mIvToBottom = (ImageView) findViewById(R.id.iv_toBottom);
		findViewById(R.id.llyt_toBottom).setOnClickListener(this);

//		mIvRefresh = (ImageView) findViewById(R.id.iv_refresh);
//		findViewById(R.id.llyt_refresh).setOnClickListener(this);

		mIvToHome = (ImageView) findViewById(R.id.iv_goGome);
		findViewById(R.id.llyt_goHome).setOnClickListener(this);

		button7 = (Button) findViewById(R.id.button7);
		button7.setOnClickListener(this);

		tv_left = (TextView) findViewById(R.id.ws_tv_titlel);
		tv_left_m = (TextView) findViewById(R.id.ws_tv_titlelm);
		String tipd = AppUtil.getRecord(IndexScreen.this,
				Constant.INDEX_TITLE_LEFT_TEXT_DEFAULT);
		if (tipd.length() > 0) {
			tv_left.setText(tipd);
		}

		tv_right = (TextView) findViewById(R.id.ws_tv_right_title);
		// tv_right.setVisibility(View.GONE);


		rl_left = (RelativeLayout) findViewById(R.id.ws_rl_titlel);
		rl_left.setClickable(true);
		rl_left.setOnClickListener(this);
		rl_left_m = (RelativeLayout) findViewById(R.id.ws_rl_titlelm);
		rl_left_m.setClickable(true);
		rl_left_m.setOnClickListener(this);

		rl_right = (RelativeLayout) findViewById(R.id.ws_rl_mess);
		rl_right.setClickable(true);
		rl_right.setOnClickListener(this);

		String tip = AppUtil.getRecord(IndexScreen.this,
				Constant.INDEX_TITLE_LEFT_TEXT);
		if (tip.length() > 0)
			tv_left.setText(tip);

		String tip1 = AppUtil.getRecord(IndexScreen.this,
				Constant.INDEX_TITLE_LEFT_TEXT2);
		if (tip1.length() > 0)
			tv_left_m.setText(tip1);
		pullToRefreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);
		pullToRefreshLayout.setOnRefreshListener(new MyListener() {
			@Override
			public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
				// 重新刷新页面
				mWebView.loadUrl(mWebView.getUrl());
				isPullUp = true;
			}
		});
		/*
		 * pullToRefreshWebView= (PullToRefreshWebView)
		 * findViewById(R.id.pull_refresh_webview); mWebView =
		 * pullToRefreshWebView.getRefreshableView();
		 */
		// mWebView = (WebView) this.findViewById(R.id.ws_webview);
		mWebView = (WebView) findViewById(R.id.content_view);
		mIvLeftIcon = (ImageView) findViewById(R.id.iv_leftIcon);
		mIvRightIcon = (ImageView) findViewById(R.id.iv_rightIcon);
		parmasMap = new HashMap<String, String>();
		parmasMap.put(Constant.USERAGENT,
				AppUtil.getUserAgent(IndexScreen.this));
		hwvc = new HtmlWebViewClient(IndexScreen.this, parmasMap, new OnLoadStartListener() {
			@Override
			public void onLoadStart() {
				if(mWebView.canGoBack()){
					mIvBack.setImageResource(R.drawable.fanghui_app_dj);
				}else{
					mIvBack.setImageResource(R.drawable.fanghui_app);
				}
				if(mWebView.canGoForward()){
					mIvForward.setImageResource(R.drawable.qianjing_app_dj);
				}else{
					mIvForward.setImageResource(R.drawable.qianjing_app);
				}
			}
		});
		hwvc.setOnJsWebViewListener(IndexScreen.this);
		mWebView.setWebViewClient(hwvc);
		hif = new HtmlInterface(this, this, mWebView);

		badge1 = new CBadgeView(this, iv_mess);
		badge1.setBadgePosition(CBadgeView.POSITION_TOP_RIGHT);

		/*
		 * swipeLayout = (SwipeRefreshLayout) this
		 * .findViewById(R.id.swipe_container); swipeLayout
		 * .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
		 * 
		 * @Override public void onRefresh() { // 重新刷新页面
		 * mWebView.loadUrl(mWebView.getUrl()); } });
		 */
		/*
		 * pullToRefreshWebView.setOnRefreshListener(new
		 * PullToRefreshBase.OnRefreshListener<WebView>() {
		 * 
		 * @Override public void onRefresh(PullToRefreshBase<WebView>
		 * refreshView) { // 重新刷新页面 mWebView.loadUrl(mWebView.getUrl());
		 * SimpleDateFormat simpleDateFormat = new
		 * SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String label =
		 * simpleDateFormat.format(System.currentTimeMillis()); // 显示最后更新的时间
		 * refreshView.getLoadingLayoutProxy() .setLastUpdatedLabel(label); }
		 * });
		 */
		
		llytEmpty = (LinearLayout) findViewById(R.id.llyt_empty);
		tvReload = (TextView) findViewById(R.id.tv_reload);
	}
	
	private void showModeCheck() {
		SharedPreferences mSharedPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		mRlytGuide = (RelativeLayout) findViewById(R.id.rlyt_guide);
		if (mSharedPreferences.getString("isFirstUse", "true").equals("true")) {
			initGuideViews();
			SharedPreferences.Editor editor = mSharedPreferences.edit();
			editor.putString("isFirstUse", "false");
			editor.commit();
		} else {
			mRlytGuide.setVisibility(View.GONE);
		}
	}

	private void initGuideViews() {
		viewPager = (ViewPager) findViewById(R.id.pager);
		LayoutInflater inflater = LayoutInflater.from(this);
		guide1 = (LinearLayout) inflater.inflate(R.layout.guide1, null);
		guide2 = (LinearLayout) inflater.inflate(R.layout.guide2, null);
		guide3 = (LinearLayout) inflater.inflate(R.layout.guide3, null);
		guide4 = (LinearLayout) inflater.inflate(R.layout.guide4, null);
		mIvPoint1 = (ImageView) findViewById(R.id.iv_point1);
		mIvPoint2 = (ImageView) findViewById(R.id.iv_point2);
		mIvPoint3 = (ImageView) findViewById(R.id.iv_point3);
		mIvPoint4 = (ImageView) findViewById(R.id.iv_point4);
		viewList = new ArrayList<View>();
		viewList.add(guide1);
		viewList.add(guide2);
		viewList.add(guide3);
		viewList.add(guide4);

		viewPager.setAdapter(guidePagerAdapter);
		guide1.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				viewPager.setCurrentItem(1);
			}
		});
		guide2.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				viewPager.setCurrentItem(2);
			}
		});
		guide3.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				viewPager.setCurrentItem(3);
			}
		});
		guide4.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mRlytGuide.setVisibility(View.GONE);
			}
		});
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int page) {
				switch (page) {
				case 0:
					mIvPoint1.setImageResource(R.drawable.icon_point_sel);
					mIvPoint2.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint3.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint4.setImageResource(R.drawable.icon_point_unsel);
					break;
			    case 1:
			    	mIvPoint1.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint2.setImageResource(R.drawable.icon_point_sel);
					mIvPoint3.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint4.setImageResource(R.drawable.icon_point_unsel);
					break;
			    case 2:
			    	mIvPoint1.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint2.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint3.setImageResource(R.drawable.icon_point_sel);
					mIvPoint4.setImageResource(R.drawable.icon_point_unsel);
			    	break;
			    case 3:
			    	mIvPoint1.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint2.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint3.setImageResource(R.drawable.icon_point_unsel);
					mIvPoint4.setImageResource(R.drawable.icon_point_sel);
			    	break;
				default:
					break;
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});
	}


	/**
	 * 
	 * 方法名：forwardUrl 功能：保存url记录 参数：
	 * 
	 * @param url
	 *            创建人：huanghaishui 创建时间：2013-12-25
	 */
	private void forwardUrl(String url) {
		if (url != null && url.length() > 0) {
			// mWebView.loadDataWithBaseURL(null, "","text/html", "utf-8",null);
			// mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
			// mWebView.clearCache(true);
			// mWebView.destroyDrawingCache();

			mWebView.loadUrl(url, parmasMap);
		}
	}

	/**
	 * 
	 * 方法名：findHistory 功能：查找历史记录 参数： 创建人：huanghaishui 创建时间：2013-12-25
	 */
	private void findHistory() {
		HUrlDaoImpl daoImpl = new HUrlDaoImpl(this);
		List<HistoryUrl> dataList = daoImpl.rawQuery(
				"select * from HistoryUrl order by id desc ", new String[] {});
		for (HistoryUrl url : dataList) {
			// Log.e("murl", url.getUrl());
		}
	}

	/**
	 * 
	 * 方法名：deleHistory 功能：删除历史记录，退出时启动 参数： 创建人：huanghaishui 创建时间：2013-12-25
	 */
	private void deleHistory() {
		HUrlDaoImpl daoImpl = new HUrlDaoImpl(this);
		List<HistoryUrl> dataList = daoImpl.rawQuery(
				"delete  from HistoryUrl  ", new String[] {});

		UploadProDataDaoImpl udaoImpl = new UploadProDataDaoImpl(
				IndexScreen.this);
		udaoImpl.rawQuery("delete  from UploadProData  ", new String[] {});
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llyt_back:
			// if(mWebView.canGoBack())
//			AppUtil.saveRecord(IndexScreen.this, Constant.OPERAFLAG, "true");
			if(mWebView.canGoBack()){
				mWebView.goBack();
			}
			// mWebView.loadUrl("javascript:window.history.go(-1)");
			break;
		case R.id.llyt_forward:
//			AppUtil.saveRecord(IndexScreen.this, Constant.OPERAFLAG, "true");
			if(mWebView.canGoForward()){
				mWebView.goForward();
			}
			break;

//		case R.id.llyt_refresh:
			// mWebView.loadUrl(mWebView.getUrl(),parmasMap);
			// DataUtil.showShortToast(IndexScreen.this, mWebView.getUrl() +
			// "");
//			if (mWebView.getUrl().indexOf("?") > -1) {
//
//				forwardUrl(mWebView.getUrl());
//			} else {
//				mWebView.reload();
//			}

//			break;
		case R.id.llyt_goHome:
			forwardUrl(url);
			break;
		case R.id.llyt_toTop:
			mWebView.scrollTo(0, 0);
			break;
		case R.id.llyt_toBottom:
			mWebView.scrollTo(
					0,
					(int) ((float) mWebView.getContentHeight() * mWebView
							.getScale()) - mWebView.getHeight());
			break;
		case R.id.button7:
			DialogUploadFile duf = new DialogUploadFile(IndexScreen.this,
					new OnChooseFileListener() {

						@Override
						public void setUploadFile(String menu, String curl) {
							if (curl != null) {
								if (curl.startsWith("sys_")) {
									if (curl.equals("sys_1")) {
										app_exit();
									} else if (curl.equals("sys_999")) {// 历史记录
										Intent intent = new Intent(
												IndexScreen.this,
												HistoryUrlScreen.class);
										startActivity(intent);
									} else if (curl.equals("sys_998")) {// 释放内存
										long before = AppUtil
												.getAvailMemory(IndexScreen.this);
										AppUtil.clearMemory(IndexScreen.this);
										long after = AppUtil
												.getAvailMemory(IndexScreen.this);
										DataUtil.showShortToast(
												IndexScreen.this,
												"已释放内存"
														+ Math.abs(after
																- before) + "M");

									} else if (curl.equals("sys_997")) {// 系统版本
										DataUtil.showShortToast(
												IndexScreen.this,
												"版本号:"
														+ getAppVersionName(IndexScreen.this)
														+ "");

									} else if (curl.equals("sys_996")) {// 照片所在路径
										DataUtil.showShortToast(
												IndexScreen.this,
												"路径:"
														+ Environment
																.getExternalStorageDirectory());
									} else if (curl.equals("sys_995")) {// 获取getNativeHeapAllocatedSize

										DataUtil.showShortToast(
												IndexScreen.this,
												android.os.Debug
														.getNativeHeapAllocatedSize()
														+ "");
									} else if (curl.equals("sys_994")) {// 获取getNativeHeapFreeSize

										DataUtil.showShortToast(
												IndexScreen.this,
												android.os.Debug
														.getNativeHeapFreeSize()
														+ "");
									} else if (curl.equals("sys_993")) {// 获取getNativeHeapSize

										DataUtil.showShortToast(
												IndexScreen.this,
												android.os.Debug
														.getNativeHeapSize()
														+ "");
									} else if (curl.equals("sys_992")) {// 清除COOKIE
										CookieSyncManager
												.createInstance(IndexScreen.this);
										CookieManager cookieManager = CookieManager
												.getInstance();

										DataUtil.showShortToast(
												IndexScreen.this, "COOKIE清除成功!");

										cookieManager.removeAllCookie();
									}
								} else {
									forwardUrl(curl);
								}
							}
						}
					});
			duf.show();
			break;
		case R.id.ws_rl_titlel:
			String urltemp = AppUtil.getRecord(IndexScreen.this,
					Constant.INDEX_TITLE_LEFT_URL);
			String urlD = AppUtil.getRecord(IndexScreen.this,
					Constant.INDEX_TITLE_LEFT_URL_DEFAULT);

			if (urltemp.length() > 0) {
				mWebView.loadUrl(urltemp, parmasMap);
			} else if (urlD.length() > 0) {
				mWebView.loadUrl(urlD, parmasMap);
			}
			break;
		case R.id.ws_rl_titlelm:
			String urltemp2 = AppUtil.getRecord(IndexScreen.this,
					Constant.INDEX_TITLE_LEFT_URL2);

			if (urltemp2.length() > 0) {
				mWebView.loadUrl(urltemp2, parmasMap);
			}
			break;
		case R.id.ws_rl_mess:
			urltemp = AppUtil.getRecord(IndexScreen.this,
					Constant.INDEX_TITLE_RIGHT_URL);
			DialogTips dt = new DialogTips(IndexScreen.this,
					new OnChooseTipListener() {

						@Override
						public void setUploadFile(String menu, String curl) {
							if (curl != null) {
								forwardUrl(curl);
							}
						}
					});

			if (urltemp.length() > 0) {
				dt.show();
				tv_right.setText("");
				iv_mess.setVisibility(View.GONE);
				badge1.setText("");
				badge1.hide();
			}
			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == HtmlInterface.REQUEST_CODE_ALUBM) {
				handleImageSelect(data);
			} else if (requestCode == 2) {
				Bundle bundle = data.getExtras();
				String result = bundle.getString("result");
				String method = bundle.getString("method");
				mWebView.loadUrl("javascript:" + method + "('" + result + "')");
			}
		}
	}

	private void handleImageSelect(Intent data) {
		if (null == data) {
			return;
		}
		ArrayList<String> images = data
				.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
		if (selecImags != null) {
			selecImags.clear();
			if (images != null) {
				selecImags.addAll(images);
			} else {
				selecImags = null;
			}
		} else {
			selecImags = images;
		}
		if (null == selecImags || 0 == selecImags.size()) {
			return;
		}
		update();
	}

	// 多张上传
	@SuppressWarnings("unchecked")
	private void update() {
		curing = 0;
		Oper = AppUtil.getRecord(IndexScreen.this,Constant.OPERATION);
		type = AppUtil.getRecord(IndexScreen.this,Constant.TYPE);
		params = AppUtil.getRecord(IndexScreen.this,Constant.PARAMS);
		gFolderName = Constant.DefaultFileName;
		if (params.length() > 0) {
			parmasMap = AppUtil.combineHttpParams(params);
			wapFrom = parmasMap.get("type");
			gFolderName = AppUtil.UnicodeToGB2312(parmasMap.get("name"));
		}
		if (params.length() > 0 && "1".equals(type)) {
			parmasMap = AppUtil.combineHttpParams(params);
			String fnum = parmasMap.get("num");
			String fmax = parmasMap.get("max_num");
			wapFrom = parmasMap.get("type");
			if (fnum != null && fmax != null) {
				int re = Integer.valueOf(fmax) - Integer.valueOf(fnum);
				if (re == 0) {
					DataUtil.showShortToast(getApplicationContext(), "文件夹："
							+ gFolderName + "图片数量已满，无法上传");
					return;
				}
				if (selecImags.size() > re) {
					DataUtil.showShortToast(getApplicationContext(), "文件夹："
							+ gFolderName + "图片容量剩余" + re + "张,您已选择"
							+ selecImags.size() + "张。");
					return;
				}
			}
		}
		proData = new UploadProData();
		UploadProDataDaoImpl daoImpl = new UploadProDataDaoImpl(this);
		proData.setTotal(selecImags.size());
		proData.setDate(DateUtil.formatDateTimeByDate(new Date()));
		proData.setCur(0);
		proData.setFailNum(0);
		if ("2".equals(type)) {
			proData.setType("修改");
		} else {
			proData.setType("上传");
		}
		proData.setFileName(gFolderName);
		gDataId = daoImpl.insert(proData);
		new UploadAsyncTask().execute(gDataId);
		Intent intent = new Intent(this, UploadInfoScreen.class);
		startActivity(intent);
	}

	@SuppressWarnings("rawtypes")
	private class UploadAsyncTask extends AsyncTask {
		@Override
		protected void onPostExecute(Object result) {
			super.onPostExecute(result);
			if (wapFrom != null) {
				finish();
			}
		}

		@Override
		protected Object doInBackground(Object... oparams) {
			int maxSize = 0;
			ArrayList<UploadInfo> infoList = new ArrayList<UploadInfo>();

			Intent intent = new Intent();
			intent.putExtra("operation", 55);
			intent.setAction(Constant.ACTION_STOA);
			sendBroadcast(intent);
			// 处理图片
			for (int m = 0; m < selecImags.size(); m++) {

				String tempPath = selecImags.get(m);
				if ("2".equals(Oper)) {
					String id = AppUtil.getRecord(IndexScreen.this,Constant.sid);
					String pid = AppUtil.getRecord(IndexScreen.this,Constant.Tpid);
					if (gpid != null) {// 有选择文件夹，则使用选择的
						pid = gpid;
					}
					String url = AppUtil.getRecord(IndexScreen.this,Constant.URL_UPLOAD);
					parmasMap = new HashMap<String, String>();
					parmasMap.put("id", id);
					parmasMap.put("p_id", pid);
					parmasMap.put("url", url);
					// 本地批量上传才有文件夹选择
					parmasMap.put("name", Constant.DefaultFileName);
					if (gFolderName != null) {
						parmasMap.put("name", gFolderName);
					}
				} else {
					if (params.length() > 0) {
						parmasMap = AppUtil.combineHttpParams(params);
						String cuurimg = parmasMap.get("cuurimg");
						String maxTemp = parmasMap.get("maxsize");
						// String this_flag = dbUtil.getRecord("this_flag");

						if (maxTemp != null && maxTemp.length() > 0) {
							maxSize = Integer.valueOf(maxTemp);
							// Integer.valueOf(this_flag);
						}

						if (cuurimg != null && cuurimg.length() > 0) {
							int temp = Integer.valueOf(cuurimg);
							temp = temp + 1 + curing;
							parmasMap.put("cuurimg", temp + "");
						}
					}
				}
				String name = "";
				int start = tempPath.lastIndexOf(File.separator) + 1;
				int last = tempPath.lastIndexOf(".");
				if(last>start&&last<=tempPath.length()){
					name = tempPath.substring(
							start,
							last);
				}
				parmasMap.put("fName", name);
				File file = ImageUpload.getInstance(IndexScreen.this)
						.readFromUri(tempPath,
								AppUtil.readPictureDegree(tempPath), maxSize);
				File sfile = ImageUpload.getInstance(IndexScreen.this)
						.readFromUriSmall(tempPath,
								AppUtil.readPictureDegree(tempPath));

				UploadInfo info = new UploadInfo();
				info.setParmasMap(parmasMap);
				info.setFile(file);
				info.setSmallFile(sfile);
				infoList.add(info);
				curing++;
			}
			proData.setInfoList(infoList);
			sendImage();
			return null;
		}
	}

	private void sendImage() {
		Thread t = new Thread() {
			@Override
			public void run() {
				UploadProDataDaoImpl daoImpl = new UploadProDataDaoImpl(
						IndexScreen.this);
				boolean isCancle = false;
				boolean isFail = false;
				Long id;
				if (gDataId == 0) {
					id = daoImpl.insert(proData);
				} else {
					id = gDataId;
				}
				AppUtil.sendMesToActivity(IndexScreen.this, 1, "");
				ArrayList<UploadInfo> list = proData.getInfoList();
				int j = 0;
				int fail = 0;
				for (int i = 0; i < list.size(); i++) {
					j++;

					UploadProData temp = daoImpl.get(id.intValue());
					if (temp == null) {
						isCancle = true;
						break;
					}
					// 防止数据库锁，暂停
					try {
						sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

					UploadInfo info = list.get(i);
					if (temp.getFlag() == 1) {
						break;
					} else {
						String result = HttpService.getInstance(
								IndexScreen.this).uploadPicture(info);
						UploadResult re = getResult(result);
						if (re.ok) {
							temp.setCur(j);
						} else {// 失败
							try {
								sleep(1500);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							String result2 = HttpService.getInstance(
									IndexScreen.this).uploadPicture(info);
							UploadResult re2 = getResult(result2);
							if (re2.ok) {
								temp.setCur(j);
							} else {
								fail++;
								isFail = true;
								temp.setRemark(re.desc);
								AppUtil.sendMesToActivity(IndexScreen.this, 3,
										re.desc);
							}

						}
						temp.setFailNum(fail);

						daoImpl.update(temp);
						// 防止数据库锁，暂停
						try {
							sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						AppUtil.sendMesToActivity(IndexScreen.this, 1, "");
					}

				}
				proData = null;
				gDataId = null;
				if (!isCancle) {
					// 上传循环结束，若记录不是中断记录，则删除
					if (!isFail) {
						try {
							sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						AppUtil.saveRecord(IndexScreen.this, "fabu", "true");
						AppUtil.sendMesToActivity(IndexScreen.this, 2, "上传成功");
					}

				} else {

				}
			}

		};
		t.start();
	}

	private static UploadResult getResult(String result) {
		UploadResult re = new UploadResult();
		if (result == null) {
			re.ok = false;
			re.desc = "网络异常，上传失败";
			return re;
		}
		// 正式
		String json = result.toString();
		try {
			String ret = new JSONObject(json).getString("ret");
			if ("0".equals(ret)) {
				re.ok = false;

			} else if ("1".equals(ret)) {
				String code = new JSONObject(json).getString("result");
				String desc = new JSONObject(json).getString("desc");
				if ("0".equals(code)) {
					re.ok = false;
					re.desc = desc;
				} else if ("1".equals(code)) {
					// 成功
				} else if ("2".equals(code)) {
					re.ok = false;
					re.desc = desc;
				}

			}
		} catch (JSONException e) {
			e.printStackTrace();
			re.ok = false;
			re.desc = "网络异常，上传失败";
			return re;
		}
		return re;
	}

	/**
	 * 
	 * 解决子Activity无法接收Activity回调的问题
	 * 
	 */
	public interface OnTabActivityResultListener {
		public void onTabActivityResult(int requestCode, int resultCode,
                                        Intent data);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (mWebView.canGoBack() && !isHome(mWebView.getUrl())) {
				mWebView.goBack(); // goBack()表示返回WebView的上一页面
			} else {
				exitBy2Click();
			}
			mLlytProgress.setVisibility(View.GONE);
			return true;
		}

		return super.dispatchKeyEvent(event);
	}
	
	//判断是否为首页
	private boolean isHome(String url){
		if(url.startsWith(Constant.getURL()+"/?") || url.startsWith(Constant.getURL()+"/default.php") 
				|| url.equals(Constant.getURL())|| url.equals(Constant.getURL()+"/"))
		{
			return true;
		}
		return false;
	}

	// 准备退出
	private static Boolean isExit = false;

	private void exitBy2Click() {
		Timer tExit = null;
		if (isExit == false) {
			isExit = true; // 准备退出
			Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
			tExit = new Timer();
			tExit.schedule(new TimerTask() {
				@Override
				public void run() {
					isExit = false; // 取消退出
				}
			}, 2000); // 如果2秒钟内没有按下返回键，则启动定时器取消掉刚才执行的任务

		} else {

			// DataUtil.deleSDFolder(CacheService.getCachePath());
			app_exit();
			// DataUtil.deleSDFolder(new File(CacheService.getCachePath()));
			// DataUtil.deleFileInFolder(ImageUpload.getInstance(IndexScreen.this.getApplicationContext()).getFileDir());
		}
	}

	public void app_exit() {

		Dialog dialog = new AlertDialog.Builder(IndexScreen.this)
				.setTitle(
						"是否退出"
								+ this.getApplication().getResources()
										.getString(R.string.app_name) + "？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						deleHistory();
						dialog.dismiss();

						LogoutUtil.getInstance().exit();
					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						dialog.dismiss();
					}
				}).create();

		dialog.show();
	}

	/*
	 * @Override protected void onNewIntent(Intent intent) {
	 * 
	 * String orderId = intent.getStringExtra("orderId"); String payResult =
	 * intent.getStringExtra("payResult");
	 * 
	 * if (!TextUtils.isEmpty(orderId) && !TextUtils.isEmpty(payResult)) { int
	 * payResultCode = Integer.parseInt(payResult); String payResultStr = ""; //
	 * 1：支付成功 2:支付失败 0： 交易取消 switch (payResultCode) { case 0: payResultStr =
	 * "交易取消"; break; case 1: payResultStr = "成功"; String partnerUserId =
	 * AppUtil.getRecord(this, Constant.PAY_USER_ID);
	 * HttpService.getInstance(IndexScreen
	 * .this.getApplicationContext()).sendPayResult(partnerUserId, orderId);
	 * break; case 2: payResultStr = "失败"; break;
	 * 
	 * default: break; } Toast.makeText(this, "订单号：" + orderId + "，支付结果：" +
	 * payResultStr, Toast.LENGTH_SHORT).show(); } super.onNewIntent(intent); }
	 */
	/**
	 * 
	 * 
	 * 类名称：UpdateQueryAsyncTask 类描述： 软件更新接口 创建人： huanghaishui 创建时间：2013-8-14
	 * 下午5:40:15 修改人：huanghaishui 修改时间：2013-8-14 下午5:40:15 修改备注：
	 * 
	 * @version
	 * 
	 */
	@SuppressWarnings("rawtypes")
	private class UpdateQueryAsyncTask extends AsyncTask {
		@Override
		protected void onPostExecute(Object result) {

			if (result != null && result.toString().length() > 0) {
				String json = result.toString();
				try {
					JSONObject update = new JSONObject(json)
							.getJSONObject("update");

					String ret = new JSONObject(json).getString("ret");

					if ("0".equals(ret)) {

					} else if ("1".equals(ret)) {
						String show = update.getString("show");
						String desc = update.getString("desc");
						String url = update.getString("url");
						if ("1".equals(show)) {
							UpdateUtil updateUtil = new UpdateUtil(
									IndexScreen.this, IndexScreen.this, desc,
									url);
							updateUtil.Update();
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
			}
			super.onPostExecute(result);
		}

		@Override
		protected Object doInBackground(Object... params) {
			return HttpService.getInstance(
					IndexScreen.this.getApplicationContext()).checkUpdate();

		}
	}

	// TODO:
	// //////////////////////// 支付 ///////////////////////////////////////////

	private class PayAsyncTask extends AsyncTask<Object, Object, Object> {
		@Override
		protected void onPostExecute(Object result) {

			if (result != null && result.toString().length() > 0) {

			} else {
			}
			super.onPostExecute(result);
		}

		@Override
		protected Object doInBackground(Object... params) {

			String orderid = AppUtil.getRecord(
					IndexScreen.this.getApplicationContext(),
					Constant.PAY_ORDER_ID);
			String partnerUserId = AppUtil.getRecord(
					IndexScreen.this.getApplicationContext(),
					Constant.PAY_USER_ID);
			LogUtil.e("paySucc", orderid + "-" + partnerUserId);
			return HttpService.getInstance(
					IndexScreen.this.getApplicationContext()).sendPayResult(
					partnerUserId, orderid);

		}
	}

	// //////////////////////// 支付 end
	// ///////////////////////////////////////////

	// //////////////////////// 推送 begin
	// ///////////////////////////////////////////

	private static final int MSG_SET_ALIAS = 1001;
	private static final int MSG_SET_TAGS = 1002;

	private void startAlias() {
		// userId = "9999999abcd";
		// userId = "hhs:linkai";
		if (StrUtils.isEmpty(userId)) {
		} else {
			mHandler.sendMessage(mHandler.obtainMessage(MSG_SET_ALIAS, userId));
		}
	}

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case MSG_SET_ALIAS:
				String[] tagsArr = userId.split(":");
				Set<String> tags = new HashSet<String>();
				for (String t : tagsArr) {
					if (StrUtils.isNotEmpty(t)) {
						LogUtil.e("pushtags", t);
						tags.add(t);
					}
				}

				JPushInterface.setAliasAndTags(IndexScreen.this, null, tags,
						mAliasCallback);
				// JPushInterface.setTags(IndexScreen.this, tags,
				// mAliasCallback);
				break;
			default:
			}
		}
	};
	
	private final TagAliasCallback mAliasCallback = new TagAliasCallback() {

		@Override
		public void gotResult(int code, String alias, Set<String> tags) {
			LogUtil.e("jpush code", code + "");
			switch (code) {

			case 0:
				JPushInterface.init(IndexScreen.this);
				break;
			case 6002:
				mHandler.sendMessageDelayed(
						mHandler.obtainMessage(MSG_SET_TAGS, tags), 1000 * 60);
				break;
			default:
			}

		}

	};

	// //////////////////////// 推送 end
	// ///////////////////////////////////////////

	private class SmsObserver extends ContentObserver {

		public SmsObserver(Handler handler) {
			super(handler);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onChange(boolean selfChange) {
			try {
				Cursor cursor = getContentResolver().query(
						Uri.parse("content://sms/"), null, null, null, null);
				cursor.moveToNext();
				String body = cursor.getString(cursor.getColumnIndex("body"));
				if (null != body && body.contains("7788收藏")) {
					int startIndex = body.indexOf("验证码") + 4;
					body = body.substring(startIndex, startIndex+6);
					Pattern pattern = Pattern.compile("[^0-9]");
					Matcher matcher = pattern.matcher(body);
					String message = matcher.replaceAll("");
					cursor.close();
					String method = "app_validate_code";
					mWebView.loadUrl("javascript:" + method + "('" + message + "')");
				}

				super.onChange(selfChange);
			} catch (Exception e) {
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(getApplicationContext(), "请查看是否已授权7788应用短信权限", Toast.LENGTH_SHORT).show();
					}
				});
			}
		}
	}

	public static boolean hasInternet(Context context) {

		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = manager.getActiveNetworkInfo();

		if (info == null || !info.isConnected()) {
			return false;
		}

		if (info.isRoaming()) {
			return true;
		}

		return true;
	}

	@Override
	public void getCurLoc(float curLoc) {
		LayoutParams params = (LayoutParams) ll_btns.getLayoutParams();
		params.height = (int) curLoc;
		ll_btns.setLayoutParams(params);
	}

	@Override
	public void onMoveFinished(int triggerId) {
		if(triggerId == 1){
			isBottomMenuShow = true;
		}else{
			isBottomMenuShow = false;
		}
	}
}
